"""
requests模块
    1、用于接口请求
    2、常用的4种请求方式：
        (1) requests.get()
        (2) requests.post()
        (3) requests.put()
        (4) requests.delete()
    以上四个方法均是调用 requests.request(method=, url=, params=, data=, **kwargs) 方法
    而以上方法是调用了最底层的 session.request(method=, url=, params=, data=, **kwargs) 方法
    两者区别：requests.request() 的每个请求是独立的，而session.request() 会自动关联所有请求的cookie信息
        def request(
            method,          请求方式，get / post / put / delete
            url,             请求路径
            params=None,     params请求参数
            data=None,       data请求参数
            headers=None,    请求头
            cookie=None,     cookie信息
            files=None,      文件上传
            auth=None,       鉴权
            timeout=None,    超时
            allow_redirects=True,  重定向
            proxies=None,    代理
            hooks=None,      钩子
            stream=None,     文件下载
            verify=None,     证书验证
            cert= None,      ca证书
            json=None,       Json参数
        ):

    postman接口请求参数格式：
        (1) form-data : 既有表单也有文件上传的参数格式
        (2) x-www-form-urlencoded : 纯表单的参数格式
        (3) raw : 包含 Text / JavaScript / JSON / HTML / XML 格式的参数
        (4) binary : 二进制文件
    requests请求响应结果respond：
        例子：res = requests.get()
        (1) res.test : 返回字符串形式的请求结果
        (2) res.json() : 返回字典形式的请求结果
        (3) res.content() : 返回字节类型的请求结果
        (4) res.status_code : 返回接口请求的状态码
        (5) res.reason : 返回接口请求的状态信息
        (6) res.cookie : 返回接口请求的cookie信息
        (7) res.encoding : 返回编码格式
        (8) res.headers : 返回响应头
        (9) res.request.xxx : 得到请求数据

    接口关联的三个层次：
        (1) 通过变量保存中间变量实现接口关联   不推荐
        (2) 通过单独的文件保存中间变量实现接口关联
        (3) 极限封装成零代码的方式实现接口关联
    接口关联的两种方式：
        (1) 正则表达式提取变量
            re.search()
            re.findall()
        (2) JsonPath提取变量
            jsonpath.jsonpath(请求结果数据"，"$.提取的变量") : 返回列表形式，没有找到则返回None

"""
import requests
import json

# 发送请求
# url = 'https://day-m.qxdaojia.com/pages/activityconfig/renewalActivity/buildRelationship'
# params = {"user_id": 1058417986676719616}
# response = requests.get(url, params=params)
# print(response)
# print(f"响应状态码：{response.status_code}")  # 响应状态码 200 500
# print(f"响应后的url路径：{response.url}")  # 响应后的url路径，有时候响应得url和请求得不一致
# print(f"响应头：{response.headers}")  # 响应头，返回的是字典的类型
# print(f"响应对应的请求头:{response.request.headers}")  # 响应对应的请求头
# print(f"响应的cookie：{response.cookies}")  # 响应的cookie（经过set-cookie动作，返回cookieJar类型）
# print(response.json())  # 响应的Json对象 如果响应结果是以json格式返回，可以转化成功python格式的数据
# print(response.text) # 响应的网页内容
# print(response.content) # 响应内容，以字节为单位
# print(response.next)  # 返回重定向链中下一个请求的 PreparedRequest 对象
# print(response.reason)  # 响应描述

# requests.get()

# --------------post请求练习
# 商城登录接口 post
# eva = 'https://day-m.qxdaojia.com'  # 环境域名
# path = '/api/malluser/user/verify/validateCode'  # 请求接口
# url = eva + path  # 完整请求路径
# json_data = {  # 请求参数
#     "mobile": "15900000000",
#     "verifyCode": "111",
#     "type": "login",
#     "thirdType": 3,
#     "isShare": "",
#     "cityCode": "4403",
#     "cityName": "深圳市",
#     "activeSource": "H5",
#     "shareSource": "grzx",
#     "registerSourceCode": "0_grzx_0_0",
#     "districtCode": "440306",
#     "registerClientSource": "web",
#     "sign_params": "APP_ID=1577498216199&TIMESTAMP=20250515185354&SIGN_TYPE=SHA256&NONCE=vd3c7s4862&SIGN=45924B7AE4B70EF9EBC1CCAE49448AEAA4E71A74D5320F7628E66C4BC572AC2C"
# }
#
# header = {"Content-Type": "application/json"}  # 请求头信息
#
# print(f"请求域名：{eva}")
# print(f"请求接口：{path}")
# print(f"完整请求路径：{url}")
#
# # post请求
# response = requests.post(url, json=json_data, headers=header)
#
# print(f"请求结果的code值：{response.status_code}")
# print(f"请求结果的文本内容：{response.text}")
# print(f"请求结果的json内容：{response.json}")
#
# # 获取响应结果中的字段值作为变量存储，比如获取token
# # 方法一：直接链式访问
# user_mall_token = response.json()['data']['access_token']
# print(f"方法一：获取接口返回的token值 = {user_mall_token}")
#
# # 方法二：分层获取
# # 获取接口响应结果
# response_data = response.json()
# if 'data' in response_data and 'access_token' in response_data['data']:
#     user_mall_token = response_data['data']['access_token']
#     print(f"方法二：获取接口返回的token值 = {user_mall_token}")
# else:
#     print("响应结果data中没有[access_token]字段")

# --------------get请求练习
# 单多多登录接口 获取token
eva = "https://day.ddm.qxdaojia.com"
path = [
    '/api/malluser/user/verify/validateCode',  # 登录接口
    '/api/repair/mini/repair/getNotification',  # 查询3.0通知接口
    '/api/kama/mini/worker/uploadHeadImage'  # 上传头像
]
url1 = eva + path[0]

json_data = {
    "mobile": "15900000023",
    "verifyCode": "1",
    "thirdType": 1,
    "type": "login",
    "cellphoneModel": "Nexus 5",
    "registerId": "8794a04f514446b4ad4a6de622ad47fa",
    "sign_params": "APP_ID=1577498216199&TIMESTAMP=20250519094138&SIGN_TYPE=SHA256&NONCE=1pj0uxlstq&SIGN=2CCA9427F1ED36A46DD31752416AD272DB37F63E6163F7842FBC1E76F2153BD8"}

headers = {  # 请求头
    'sourceType': 'web',
    'withCredentials': "true",
    'content-type': 'application/json',
    'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko)',
    'Accept': "*/*",
    'Accept-Encoding': 'gzip, deflate, br',
    'Connection': 'keep-alive'

}

print(url1)
response_1 = requests.post(url1, json=json_data, headers=headers)
#
print(f"登录接口的请求结果的code值：{response_1.status_code}")
print(f"登录接口的请求结果的文本内容：{response_1.text}")
print(f"登录接口的请求结果的json内容：{response_1.json}")

# 获取响应结果中的字段值作为变量存储，比如获取token
# 方法一：直接链式访问
user_mall_token = response_1.json()['data']['access_token']
print(f"方法一：获取登录接口返回的token值 = {user_mall_token}")

# 方法二：分层获取
# 获取接口响应结果
response_data = response_1.json()
if 'data' in response_data and 'userId' in response_data['data']:
    user_id = response_1.json()['data']['userId']
    print(f"方法二：获取登录接口返回的uer_id值 = {user_id}")

# get请求 无请求参数
url2 = eva + path[1]
headers = {'authorization': f'Bearer {user_mall_token}'}  # 将登录接口获取到的token放在下一个接口的请求头中
response_2 = requests.get(url2, headers=headers)
requests_data = response_2.json()
print(f"获取通知接口的请求响应code：{response_2.status_code}")
print(f"获取通知接口的请求响应结果：{requests_data}")

# get请求 有请求参数
url3 = eva + path[2]
headers = {'authorization': f'Bearer {user_mall_token}'}
param = {
    'headImageUrl': 'https://cloudimage.qxdaojia.com/ddd/1745553587005-54d4d427-6530-457c-afe0-8c7b3b2ef778.png',
    'userId': f'{user_id}'
}
response_3 = requests.get(url3, headers=headers, params=param)
print(f"上传头像接口的请求响应code：{response_3.status_code}")
print(f"上传头像接口的请求响应内容：{response_3.json()}")

# # 参数是表单
# eva = "https://day.ddm.qxdaojia.com"
# path = '/api/file/oss/uploadFileToSsoEncrypt'  # 单多多上传图片转换接口
# url4 = eva + path
# file_path = r'C:\Users\Administrator\Desktop\图片\0-正.jpg'  # 原始字符串写法
# with open(file_path, 'rb') as f:
#     files = {
#         'fileDir': 'real/ddd',  # 非文件字段
#         'files': ('0-正.jpg', f, 'image/jpeg')   # 文件字段
#     }
#     headers = {
#         'cookie': 'sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%221105186335603294208%22%2C%22first_id%22%3A%22195188ae01315a3-0ff218050e89cc-4201541c-332800-195188ae014111a%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTk1MTg4YWUwMTMxNWEzLTBmZjIxODA1MGU4OWNjLTQyMDE1NDFjLTMzMjgwMC0xOTUxODhhZTAxNDExMWEiLCIkaWRlbnRpdHlfbG9naW5faWQiOiIxMTA1MTg2MzM1NjAzMjk0MjA4In0%3D%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%24identity_login_id%22%2C%22value%22%3A%221105186335603294208%22%7D%2C%22%24device_id%22%3A%22195188ae01315a3-0ff218050e89cc-4201541c-332800-195188ae014111a%22%7D; token=7b4580f2-978b-43f8-8ec4-7275e9f7a40d'
#     }
#
# response_4 = requests.post(url4, data=files, headers=headers)
# print(f"请求路径：{url4}")
# print(f"上传图片转换接口的请求响应code：{response_4.status_code}")
# print(f"上传图片转换接口的请求响应内容：{response_4.json()}")

# 参数是表单
eva = "https://day-manage.qxdaojia.com"
path = '/api/excellentmall/corp/media/upload/image'  # 单多多上传图片转换接口
url4 = eva + path


url4 = 'https://fat-manage.qxdaojia.com/api/excellentmall/corp/media/upload/image'
param = {
    'applicationName': 'QXTECH-QWMANAGER'
}
data = {
    'file': r'C:\Users\Administrator\Desktop\图片\0-正.jpg'
}
response_4 = requests.post(url4, params=param, data=data)
print(f"请求路径：{url4}")
print(f"上传图片转换接口的请求响应code：{response_4.status_code}")
print(f"上传图片转换接口的请求响应内容：{response_4.json()}")

# post上传文件练习
# 请求路径
url = "https://day-m.qxdaojia.com/api/excellentmall/corp/media/upload/image?applicationName=QXTECH-QWMANAGER"
file_path = r"C:\Users\Administrator\Desktop\图片\1png.png"       # 本地文件路径

payload = {}        # 请求体
files = [        # 文件参数
    ('file', ('1png.png', open(file_path, 'rb'), 'image/png'))
]
headers = {}   # 请求头

# post请求
# response = requests.request("POST", url, headers=headers, data=payload, files=files)
response = requests.post(url, headers=headers, data=payload, files=files)
print(f'上传图片文件接口请求响应code值：{response.status_code}')
print(f'上传图片文件接口请求响应内容：{response.text}')
